#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据备份恢复功能
"""

import os
import json
import shutil
from datetime import datetime
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, 
                             QLabel, QPushButton, QFileDialog, 
                             QMessageBox, QTextEdit)
from PyQt5.QtCore import Qt
from database import Database


class BackupWidget(QWidget):
    """数据备份恢复面板"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout()
        
        # 备份区域
        backup_layout = QVBoxLayout()
        backup_layout.addWidget(QLabel("数据备份"))
        
        backup_button = QPushButton("备份数据")
        backup_button.clicked.connect(self.backup_data)
        backup_layout.addWidget(backup_button)
        
        layout.addLayout(backup_layout)
        
        # 恢复区域
        restore_layout = QVBoxLayout()
        restore_layout.addWidget(QLabel("数据恢复"))
        
        restore_button = QPushButton("从文件恢复")
        restore_button.clicked.connect(self.restore_data)
        restore_layout.addWidget(restore_button)
        
        layout.addLayout(restore_layout)
        
        # 日志区域
        layout.addWidget(QLabel("操作日志"))
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        layout.addWidget(self.log_text)
        
        self.setLayout(layout)
        
    def backup_data(self):
        """备份数据"""
        # 获取保存文件路径
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存备份文件", f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", 
            "JSON Files (*.json)")
        
        if not file_path:
            return
            
        try:
            # 导出所有数据
            db = Database()
            data = db.export_all_data()
            
            # 保存到文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
                
            self.log(f"数据已备份到: {file_path}")
            QMessageBox.information(self, "备份成功", f"数据已成功备份到:\n{file_path}")
        except Exception as e:
            error_msg = f"备份失败: {str(e)}"
            self.log(error_msg)
            QMessageBox.critical(self, "备份失败", error_msg)
            
    def restore_data(self):
        """从文件恢复数据"""
        # 选择备份文件
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择备份文件", "", "JSON Files (*.json)")
        
        if not file_path:
            return
            
        # 确认恢复操作
        reply = QMessageBox.question(
            self, "确认恢复", 
            "恢复数据将覆盖当前所有数据，确定要继续吗？\n\n"
            "注意：此操作不可撤销，请确保已备份重要数据。", 
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            
        if reply != QMessageBox.Yes:
            return
            
        try:
            # 从文件读取数据
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                
            # 导入数据
            db = Database()
            db.import_all_data(data)
            
            self.log(f"数据已从 {file_path} 恢复")
            QMessageBox.information(self, "恢复成功", "数据已成功恢复")
        except Exception as e:
            error_msg = f"恢复失败: {str(e)}"
            self.log(error_msg)
            QMessageBox.critical(self, "恢复失败", error_msg)
            
    def log(self, message):
        """记录日志"""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.log_text.append(f"[{timestamp}] {message}")